package com.hnyyac.ad.mds

import android.annotation.SuppressLint
import android.app.Activity
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.hnyyac.ad.mds.cache.CacheAdLoadedManager
import com.hnyyac.ad.mds.cache.CacheHelper
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

@SuppressLint("StaticFieldLeak")
internal object KadControler {
    private val TAG = "KadControler"
    lateinit var context: Activity
    var cpShowIds = emptyList<String>()
    var videoShowIds = emptyList<String>()
    var isNetworkAvailable: Boolean = true
//        get() {
//            val activeNetworkInfo = connectivityManager.activeNetworkInfo
//            return activeNetworkInfo != null && activeNetworkInfo.isConnected
//        }
    // 新增网络状态监听
//    private val connectivityManager by lazy {
//        context?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
//    }

    // 网络状态LiveData
    private val _networkStatus = MutableLiveData<Boolean>()
    var networkStatus: LiveData<Boolean> = _networkStatus
    // 初始化网络监听
//    fun init(context: Context) {
//        if (::context.isInitialized) {
//            return
//        }
//        this.context = context
//      //  registerNetworkCallback()
//    }
    // 注册网络状态监听
//    private fun registerNetworkCallback() {
//        val request = NetworkRequest.Builder().build()
//        connectivityManager.registerNetworkCallback(request, object : ConnectivityManager.NetworkCallback() {
//            override fun onAvailable(network: Network) {
//                _networkStatus.postValue(true)
//                onNetworkRestored()
//                isNetworkAvailable=true
//            }
//
//            override fun onLost(network: Network) {
//                _networkStatus.postValue(false)
//                isNetworkAvailable=false
//            }
//        })
//    }
    fun loadAd(activity: Activity,position: Int, adType: IAdType): LiveData<IAdView?> {
        if(!isNetworkAvailable){
           // Toast.makeText(context,"网络异常，请检查网络",Toast.LENGTH_SHORT).show()
        }
        if (!::context.isInitialized) {
            LLogs.err(TAG, "KadControler未初始化，请先调用init()方法。")
            return MutableLiveData<IAdView?>()
        }
        Log.e(TAG,"当前的位置是:$position")
        val liveData = MutableLiveData<IAdView?>()
        LLogs.info(TAG,"load 广告 >>>")
        GlobalScope.launch {
            LLogs.info(TAG,"load 广告 >>>")
            val ad = CacheHelper.popAd(adType,position)
            ad?.setPosition(position)
          // 在返回广告前设置位置
            LLogs.info(TAG,"load 广告, 结果: ${ad?.toString()}")
            liveData.postValue(ad)
            // 如果缓存为空，尝试补充广告
            if (ad == null) {
                LLogs.info(TAG, "缓存为空，开始补充广告")
               // CacheHelper.fillCache()
                if (adType==IAdType.reward_video){
                    CacheHelper.fillCache_video(position)
                }
                if (adType==IAdType.interstitial){
                    CacheHelper.fillCache_chapin(position)
                }



            }
        }
        return liveData
    }

    /**
     * 首次检查补充缓存
     */
    fun fristFillCache() {
        CacheHelper.fillCache_video(0)
        CacheHelper.fillCache_chapin(0)
       // CacheHelper.fillCache()
    }

    internal fun pushUAdViewCache(uadView: IAdView) {
        CacheHelper.pushCache(uadView)
        CacheAdLoadedManager.onAdLoadSucc(uadView)
    }


    // 网络恢复时的处理
    private fun onNetworkRestored() {
        LLogs.info(TAG, "网络恢复，开始补充广告缓存")
     //   CacheHelper.fillCache()
    }
}